<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="标题" prop="title" label-width="40px">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入公告标题"
          clearable
          size="small"
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否置顶" prop="topStatus">
        <el-select v-model="queryParams.topStatus" placeholder="请选择" clearable size="small" style="width: 100px">
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="syncTime">
        <el-date-picker
          v-model="daterangeSyncTime"
          size="small"
          clearable
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="所属板块" prop="sectionId">
        <el-select v-model="queryParams.sectionId" clearable placeholder="请选择" style="width: 120px">
          <el-option
            v-for="item in sectionDict"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['community:section:add']"
          type="primary"
          size="small"
          @click="sectionOpen = true"
        >公告板块管理</el-button>
      </el-col>
      <el-col :span="5">
        <el-button-group>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAdd"
          />
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            :disabled="single"
            @click="handleUpdate"
          />
          <el-button
            type="primary"
            size="small"
            icon="el-icon-delete"
            :disabled="multiple"
            @click="handleDelete"
          />
        </el-button-group>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="contentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" align="center" width="50" />
      <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="所属板块" align="center" prop="sectionId" :formatter="showSectionName" />
      <el-table-column label="置顶状态" align="center" prop="topStatus" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.topStatus===1" type="danger">置顶</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="author" />
      <el-table-column label="创建时间" sortable align="center" prop="syncTime" width="180" />
      <el-table-column label="阅读量" align="center" prop="viewNumber" width="80" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row type="flex" justify="space-between">
          <el-col :span="14">
            <el-form-item label="公告标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入公告标题" maxlength="50" show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="所属板块" prop="sectionId">
              <el-select v-model="form.sectionId" placeholder="请选择板块">
                <el-option
                  v-for="item in sectionDict"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-form-item label="公告标题" prop="title">-->
<!--          <el-input v-model="form.title" placeholder="请输入公告标题" maxlength="50" show-word-limit/>-->
<!--        </el-form-item>-->
        <el-form-item label="公告内容" prop="content">
          <editor v-model="form.content" height="250"/>
<!--          <editor v-model="form.content" :upload-url="uploadUrl" :min-height="192" style="max-height: 280px; overflow-y: scroll" />-->
<!--          <EditorDc v-model="form.content" :min-height="192" style="max-height: 280px; overflow-y: scroll"/>-->
        </el-form-item>
        <el-form-item label="是否置顶">
          <el-radio-group v-model="form.topStatus">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="所属板块" prop="sectionId">-->
<!--          <el-select v-model="form.sectionId" placeholder="请选择板块">-->
<!--            <el-option-->
<!--              v-for="item in sectionDict"-->
<!--              :key="item.value"-->
<!--              :label="item.label"-->
<!--              :value="item.value"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 管理公告板块对话框 -->
    <el-dialog title="公告板块管理" :visible.sync="sectionOpen" width="800px" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['community:section:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleSectionAdd"
          >新增</el-button>
        </el-col>
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" style="float: right; margin-right: 10px" @click="getSectionList()" />
        </el-tooltip>
      </el-row>
      <el-table v-loading="loading" :data="sectionList" max-height="450px" @selection-change="handleSelectionChange">
        <el-table-column type="index" align="center" width="50" />
        <el-table-column label="板块名称" align="center" prop="sectionName" />
        <el-table-column label="创建者" align="center" prop="creater" />
        <el-table-column label="创建时间" align="center" prop="syncTime" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['community:section:remove']"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleSectionDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 新增公告板块对话框 -->
    <el-dialog title="新建板块" :visible.sync="sectionAddOpen" width="500px" append-to-body>
      <el-form ref="sectionForm" :model="sectionForm" :rules="rules" label-width="80px">
        <el-form-item label="板块名称" prop="sectionName">
          <el-input v-model="sectionForm.sectionName" placeholder="请输入板块名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSectionForm">确 定</el-button>
        <el-button @click="sectionAddOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { previewContent, getContent, delContent, addContent, updateContent } from '@/api/notice/notice'
import { listSection, delSection, addSection } from '@/api/notice/notice'
import Editor from '@/components/Editor'
import EditorDc from '@/components/EditorDc'
import { dateFormat } from '@/utils/dateUtils'

export default {
  name: 'Content',
  components: {
    Editor,
    EditorDc
  },
  data() {
    /** 新建板块名称的检验条件：非空、唯一 */
    const sectionNameUnique = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('板块名称不能为空'))
      }
      for (let i = 0; i < this.sectionDict.length; i++) {
        if (this.sectionDict[i].label === value) {
          callback(new Error('板块名称不可重复'))
        }
      }
      callback()
    }
    return {
      // uploadUrl: process.env.VUE_APP_BASE_API + '/community/notice/uploadFile',
      // uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      // 遮罩层
      loading: false,
      sectionLoading: false,
      noticeLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 公告板块原始列表
      sectionList: [],
      // 公告板块字典
      sectionDict: [],
      // 总条数
      total: 0,
      // 公告列表表格数据
      contentList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示公告板块相关的弹出层
      sectionOpen: false,
      sectionAddOpen: false,
      // 创建时间时间范围
      daterangeSyncTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        sectionId: null,
        topStatus: null,
        syncTime: null,
        communityId: null
      },
      // 板块查询参数
      sectionQueryParams: {
        sectionName: null,
        creater: null,
        syncTime: null,
        communityId: null
      },
      // 表单参数
      form: {
        topStatus: 0,
      },
      sectionForm: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: '公告标题不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '公告内容不能为空', trigger: 'blur' }
        ],
        sectionId: [
          { required: true, message: '所属板块不能为空', trigger: 'blur' }
        ],
        sectionName: [
          { validator: sectionNameUnique, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getSectionList()
    this.getList()
  },
  methods: {
    /** 加载公告板块信息 **/
    getSectionList() {
      this.sectionLoading = true
      listSection(this.sectionQueryParams).then(response => {
        if (response.code === 200) {
          this.sectionList = response.data
          const tmp = response.data
          this.sectionDict = []
          for (let i = 0; i < tmp.length; i++) {
            this.sectionDict.push({
              label: tmp[i].sectionName,
              value: tmp[i].sectionId
            })
          }
        } else {
          console.log('section load error', response.msg)
        }
        this.sectionLoading = false
      })
    },
    /** 删除板块 */
    handleSectionDelete(row) {
      const sectionIds = row.sectionId
      this.$confirm('删除板块将同步删除该板块下所有公告，是否确认删除该公告板块？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delSection(sectionIds)
      }).then(() => {
        this.getSectionList()
        this.msgSuccess('删除成功')
      })
    },
    /** 新建板块 */
    handleSectionAdd() {
      this.sectionForm = {
        sectionId: null,
        sectionName: null,
        creater: null,
        syncTime: null,
        communityId: null
      }
      this.resetForm('sectionForm')
      this.sectionAddOpen = true
    },
    /** 新建板块-提交 **/
    submitSectionForm() {
      this.$refs['sectionForm'].validate(valid => {
        if (valid) {
          const createTime = new Date()
          this.sectionForm.syncTime = dateFormat('YYYY-mm-dd HH:MM:SS', createTime)
          addSection(this.sectionForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess('板块创建成功')
              this.sectionAddOpen = false
              this.getSectionList()
            } else {
              this.msgError('板块创建失败，请稍后再试')
            }
          })
        }
      })
    },
    /** 查询公告缩略信息列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (this.daterangeSyncTime != null && this.daterangeSyncTime !== '') {
        this.queryParams.params['beginSyncTime'] = this.daterangeSyncTime[0]
        this.queryParams.params['endSyncTime'] = this.daterangeSyncTime[1]
      }
      previewContent(this.queryParams).then(response => {
        this.contentList = response.rows
        // console.log(this.contentList)
        this.total = response.total
        this.loading = false
      })
    },
    /** 将表格显示的板块id转换为板块名 */
    showSectionName(row) {
      for (let i = 0; i < this.sectionDict.length; i++) {
        if (this.sectionDict[i].value === row.sectionId) {
          return this.sectionDict[i].label
        }
      }
      return null
    },
    // 表单重置
    reset() {
      this.form = {
        noticeId: null,
        title: null,
        content: null,
        sectionId: null,
        topStatus: 0,
        picUrl: null,
        author: null,
        syncTime: null,
        viewNumber: null,
        communityId: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      // 单独处理创建时间范围的筛选条件
      this.daterangeSyncTime = []
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.noticeId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新建公告 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加公告列表'
    },
    /** 新建公告-取消 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 修改公告 */
    handleUpdate(row) {
      this.reset()
      const noticeId = row.noticeId || this.ids
      getContent(noticeId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改公告列表'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.noticeId != null) {
            updateContent(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            const createTime = new Date()
            this.form.syncTime = dateFormat('YYYY-mm-dd HH:MM:SS', createTime)
            addContent(this.form).then(response => {
              this.msgSuccess('公告创建成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除公告 */
    handleDelete(row) {
      const noticeIds = row.noticeId || this.ids
      this.$confirm('是否确认删除该公告？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delContent(noticeIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
  }
}
</script>
